package com.jianguo.web.controller.api;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.jianguo.common.core.controller.BaseController;
import com.jianguo.common.core.domain.AjaxResult;
import com.jianguo.user.domain.PzBalance;
import com.jianguo.user.domain.PzUser;
import com.jianguo.user.domain.UserInfo;
import com.jianguo.user.service.IPzBalanceService;
import com.jianguo.user.service.IPzUserService;
import com.jianguo.web.controller.tool.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.concurrent.TimeUnit;

/**
 * @author xjunjie
 * @date 2024/03/12
 */
@RestController
@RequestMapping("/api/user")
public class UserApi extends BaseController {
    @Autowired
    private IPzUserService pzUserService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private IPzBalanceService pzBalanceService;

    /**
     * 登录
     * @param pzUser
     * @return
     */
    @PostMapping(value = "/login")
    public AjaxResult userLogin(@RequestBody PzUser pzUser) throws NoSuchAlgorithmException {
        pzUser.setPassword(MD5Util.encrypt(pzUser.getPassword()));
        LambdaQueryWrapper<PzUser> queryWrapper = new LambdaQueryWrapper<PzUser>()
                .eq(PzUser::getAccount, pzUser.getAccount())
                .eq(PzUser::getPassword, pzUser.getPassword());
        PzUser user = pzUserService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(user)){
            return AjaxResult.error("账号或密码错误");
        }
        return success();
    }

    // 验证码登录
    @GetMapping(value = "/codeLogin")
    public AjaxResult codeLogin(String account, String code) {
        // 验证码校验
        String codeRedis = redisTemplate.opsForValue().get(account);
        if (ObjectUtil.isEmpty(codeRedis) || !code.equals(codeRedis)){
            return AjaxResult.error("验证码错误");
        }

        // 登录成功
        return success();
    }

    // 注册
    @PostMapping(value = "/register")
    public AjaxResult register(@RequestBody PzUser pzUser) throws NoSuchAlgorithmException {
        // 校验账号是否存在
        LambdaQueryWrapper<PzUser> queryWrapper = new LambdaQueryWrapper<PzUser>()
               .eq(PzUser::getAccount, pzUser.getAccount());
        PzUser user = pzUserService.getOne(queryWrapper);
        if (ObjectUtil.isNotEmpty(user)){
            return AjaxResult.error("账号已存在");
        }
//        // 校验验证码
//        String codeRedis = redisTemplate.opsForValue().get(pzUser.getAccount());
//        if (ObjectUtil.isEmpty(codeRedis) || !pzUser.getCode().equals(codeRedis)){
//            return AjaxResult.error("验证码错误");
//        }
        // 注册
        pzUser.setPic("1").setStatus(0L).setNickname(pzUser.getAccount());
        // 密码加密
        String password = pzUser.getPassword();
        pzUser.setPassword(MD5Util.encrypt(password));
        pzUserService.save(pzUser);
        // 保存余额
        PzBalance pzBalance = new PzBalance();
        pzBalance.setUserid(pzUser.getId());
        pzBalance.setBalance(0L);
        pzBalanceService.save(pzBalance);
        return success();
    }

    /**
     * 获取用户详细信息
     * @param account
     * @return
     */
    @GetMapping(value = "/userInfo")
    public AjaxResult getUserInfo(String account){
        if (ObjectUtil.isEmpty(account)){
            return error();
        }

        LambdaQueryWrapper<PzUser> queryWrapper = new LambdaQueryWrapper<PzUser>().eq(PzUser::getAccount, account);
        PzUser user = pzUserService.getOne(queryWrapper);

        UserInfo userInfo = BeanUtil.copyProperties(user, UserInfo.class);

        // 获取余额
        PzBalance balance = pzBalanceService.getOne(new LambdaQueryWrapper<PzBalance>().
                eq(PzBalance::getUserid, user.getId()));
        // 设置余额
        userInfo.setBalance(balance.getBalance());

        return success(userInfo);
    }

    // 更新用户信息
    @PutMapping(value = "/update")
    public AjaxResult updateUser(@RequestBody PzUser user){
        if (ObjectUtil.isEmpty(user.getId())){
            return error(":id不能为空");
        }
        return success(pzUserService.updateById(user));
    }

    // 生成验证码
    @GetMapping(value = "/generateCode")
    public AjaxResult generateCode(String account) {
        if (ObjectUtil.isEmpty(account)) {
            return error();
        }
        //判断账号是否存在
        LambdaQueryWrapper<PzUser> queryWrapper = new LambdaQueryWrapper<PzUser>().eq(PzUser::getAccount, account);
        PzUser user = pzUserService.getOne(queryWrapper);
        if (ObjectUtil.isEmpty(user)){
            return AjaxResult.error("账号不存在");
        }
        // 随机生成
        String code = RandomUtil.randomNumbers(6);    // 随机生成6位数字验证码

        // 保存验证码到redis
         redisTemplate.opsForValue().set(account, code, 5, TimeUnit.MINUTES);

        return success(code);
    }

    // 生成验证码
    @GetMapping(value = "/generateCode1")
    public AjaxResult generateCode1(String account) {
        if (ObjectUtil.isEmpty(account)) {
            return error();
        }
        // 随机生成
        String code = RandomUtil.randomNumbers(6);    // 随机生成6位数字验证码

        // 保存验证码到redis
        redisTemplate.opsForValue().set(account, code, 5, TimeUnit.MINUTES);

        return success(code);
    }


}
